<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Simplelogin Class
 *
 * Makes authentication simple
 *
 * Simplelogin is released to the public domain
 * (use it however you want to)
 *
 * Simplelogin expects this database setup
 * (if you are not using this setup you may
 * need to do some tweaking)
 *

 #This is for a MySQL table
 CREATE TABLE `users` (
 `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `username` VARCHAR( 64 ) NOT NULL ,
 `password` VARCHAR( 64 ) NOT NULL ,
 UNIQUE (
 `username`
 )
 );

 *
 */
class Simplelogin {
    var $CI;
    var $user_table = 'users';

    function Simplelogin() {
        // get_instance does not work well in PHP 4
        // you end up with two instances
        // of the CI object and missing data
        // when you call get_instance in the constructor
        //$this->CI =& get_instance();
    }

    /**
     * Crea el usuario
     */
    function create(
            $name='',
            $username='',
            $password='',
            $usertype='ecommerce',
            $email='',
            $gid='18',
            $registerDate='',
            $activation='1',
            $address_type='BT',
            $phone_1='',
            $fax='',
            $address_1='',
            $city='',
            $state='',
            $zip='',
            $extra_field_1='',
            $extra_field_2='',
            $extra_field_3='',
            $extra_field_4='',
            $extra_field_5='',
            $codprv='',
            $codtrat='',
            $codvencom='',
            $codcondi='',
            $codlis='',
            $mailv=''
    ) {

        $username =  sprintf("%05s",$username) ;

        //Put here for PHP 4 users
        $this->CI =& get_instance();

        //Make sure account info was sent
        if($username == '' OR $password == '') {
            echo "mal pass user";
            return false;
        }

        //Check against user table
        $this->CI->db->where('username', $username);
        $query = $this->CI->db->getwhere($this->user_table);

        //Encrypt password
        $password = md5($password);

        //Insert account into the database
        $data = array(
                'name' => $name,
                'username' => $username,
                'password' => $password,
                'usertype' => $usertype,
                'email' => $email,
                'gid' => $gid,
                'registerDate' => $registerDate,
                'activation' => $activation,
                'address_type' => $address_type,
                'phone_1' => $phone_1,
                'fax' => $fax,
                'address_1' => $address_1,
                'city' => $city,
                'state' => $state,
                'zip' => $zip,
                'extra_field_1' => $extra_field_1,
                'extra_field_2' => $extra_field_2,
                'extra_field_3' => $extra_field_3,
                'extra_field_4' => $extra_field_4,
                'extra_field_5' => $extra_field_5,
                'codprv' => $codprv,
                'codtrat' => $codtrat,
                'codvencom' => $codvencom,
                'codcondi' => $codcondi,
                'codlis' => $codlis,
                'mailv' => $mailv
        );

        $this->CI->db->set($data);
        //echo $this->CI->db->insert_string($this->user_table, $data);
        if(!$this->CI->db->insert($this->user_table)) {
            //There was a problem!
            echo "hay problemas";
            return false;
        }

        $user_id = $this->CI->db->insert_id();

        //Automatically login to created account
        $auto_login=true;
        if($auto_login) {
            //Destroy old session
            $this->CI->session->sess_destroy();

            //Create a fresh, brand new session
            $this->CI->session->sess_create();

            //Set session data
            $this->CI->session->set_userdata(array('id' => $user_id,
                    'username' => $username,
                    'logged_in' => true
            ));
        }

        //Login was successful
        return true;
    }


    function callback_username_check($str) {
        $this->CI =& get_instance();

        //Check against user table
        $this->CI->db->where('username', $str);
        $query = $this->CI->db->getwhere($this->user_table);

        if ($query->num_rows() > 0) {
            //username already exists
            $this->validation->set_message('username_check', 'The %s field can not be the word "test"');
            return FALSE;

            return false;
        }else {
            return true;
        }
    }

    /**
     *
     *
     * Delete user
     *
     * @access	public
     * @param integer
     * @return	bool
     */
    function delete($user_id) {
        //Put here for PHP 4 users
        $this->CI =& get_instance();

        if(!is_numeric($user_id)) {
            //There was a problem
            return false;
        }

        if($this->CI->db->delete($this->user_table, array('id' => $user_id))) {
            //Database call was successful, user is deleted
            return true;
        } else {
            //There was a problem
            return false;
        }
    }


    /**
     * Login and sets session variables
     *
     * @access	public
     * @param	string
     * @param	string
     * @return	bool
     */
    function login($email = '', $password = '', $letra = '', $numero = '', $tarjeta_dato = '') {
        if($letra=='A') {
            $letra=0;
        } elseif ($letra=='B') {
            $letra=1;
        } elseif ($letra=='C') {
            $letra=2;
        } elseif ($letra=='D') {
            $letra=3;
        } elseif ($letra=='E') {
            $letra=4;
        } elseif ($letra=='F') {
            $letra=5;
        } elseif ($letra=='G') {
            $letra=6;
        } elseif ($letra=='H') {
            $letra=7;
        } elseif ($letra=='I') {
            $letra=8;
        } elseif ($letra=='J') {
            $letra=9;
        }

        //Put here for PHP 4 users
        $this->CI =& get_instance();

        //Make sure login info was sent
        if($email == '' OR $password == '') {
            return false;
        }

        //Check if already logged in
        if($this->CI->session->userdata('email') == $email) {
            return false;
        }

        //Check against user table
        $this->CI->db->where('email', $email);
        $query = $this->CI->db->getwhere($this->user_table);

        if ($query->num_rows() > 0) {
            $row = $query->row_array();

            //Check against password
            if(md5($password) != $row['password']) {
                return false;
            }
            
            //Check tarjeta
            $this->CI->config->load('config_intranet');
            $rango_ip           = $this->CI->config->item('rango_ip');
            $ip                 = $this->CI->input->ip_address();
            $ip_cliente         = explode(".",$ip);
            $ip_cliente_interna = $ip_cliente[0].".".$ip_cliente[1];

           if ($rango_ip!=$ip_cliente_interna && "0.0"!=$ip_cliente_interna) {
                $tarjeta = array();
                $tarjeta = unserialize($row['params']);
                if(md5($tarjeta_dato) != $tarjeta[$numero][$letra]) {
  //                  return false;
                }
           }

            //          echo md5($tarjeta_dato)."--".$tarjeta[$numero][$letra];
            //          exit();

            //Destroy old session
            $this->CI->session->sess_destroy();

            //Create a fresh, brand new session
            $this->CI->session->sess_create();

            //Remove the password field
            unset($row['password']);

            //Set session data
            $this->CI->session->set_userdata(array('id' => $row['id'],
                    'email' => $row['email'],
                    'username' => $row['username'],
                    'password' => base64_encode($password),
 //                   'password' => $password,
                    'perms' => $row['perms'],
                    'logged_in' => true
            ));

            //Login was successful
            return true;
        } else {
            //No database result found
            return false;
        }

    }

    /**
     * Logout user
     *
     * @access	public
     * @return	void
     */
    function logout() {
        //Put here for PHP 4 users
        $this->CI =& get_instance();

        //Destroy session
        $this->CI->session->sess_destroy();
    }
}
?>